#include "../../core/base/file_io.h"

#include <stdio.h>
#include <stdlib.h>
#include <string>

#include <android/asset_manager.h>


extern AAssetManager* g_assetMgr;

struct FILE_HOLDER {
	AAsset* pFile;
	unsigned int size;
	void* pFileData;
	FILE_HOLDER() {pFile = NULL; pFileData = NULL;}
};

KFileReader::KFileReader()
{
	mpFileDesc = new FILE_HOLDER;
}

KFileReader::KFileReader(const char* filename)
{
	mpFileDesc = new FILE_HOLDER;
	OpenFile(filename);
}

KFileReader::~KFileReader()
{
	CloseFile();
	ReleaseCopyInMemory();
	FILE_HOLDER* pFileHolder = (FILE_HOLDER*)mpFileDesc;
	delete pFileHolder;
}

bool KFileReader::OpenFile(const char* filename)
{
	FILE_HOLDER* pFileHolder = (FILE_HOLDER*)mpFileDesc;
	if (pFileHolder->pFile)
		CloseFile();
	pFileHolder->pFile = AAssetManager_open(g_assetMgr, filename, AASSET_MODE_BUFFER);
	if (pFileHolder->pFile == NULL)
		return false;
		
	pFileHolder->size = (unsigned int)AAsset_getLength(pFileHolder->pFile);
	return true;
}

void KFileReader::CloseFile()
{
	FILE_HOLDER* pFileHolder = (FILE_HOLDER*)mpFileDesc;
	if (pFileHolder->pFile == NULL) {
		AAsset_close(pFileHolder->pFile);
		pFileHolder->pFile = NULL;
	}
}

bool KFileReader::IsFileOpen() const
{
	FILE_HOLDER* pFileHolder = (FILE_HOLDER*)mpFileDesc;
	return pFileHolder->pFile != NULL;
}

bool KFileReader::Read(void* pOutData, unsigned int size)
{
	FILE_HOLDER* pFileHolder = (FILE_HOLDER*)mpFileDesc;
	if (NULL == pFileHolder->pFile)
		return false;
	return (int)size == AAsset_read(pFileHolder->pFile, pOutData, size);
}

bool KFileReader::Skip(unsigned int size)
{
	FILE_HOLDER* pFileHolder = (FILE_HOLDER*)mpFileDesc;
	if (NULL == pFileHolder->pFile)
		return false;
	return (AAsset_seek(pFileHolder->pFile, size, SEEK_CUR) != -1);
}

void KFileReader::ResetRead()
{
	FILE_HOLDER* pFileHolder = (FILE_HOLDER*)mpFileDesc;
	AAsset_seek(pFileHolder->pFile, 0, SEEK_SET);
}

unsigned int KFileReader::GetFileSize() const
{
	FILE_HOLDER* pFileHolder = (FILE_HOLDER*)mpFileDesc;
	return pFileHolder->size;
}

void* KFileReader::CopyIntoMemory()
{
	FILE_HOLDER* pFileHolder = (FILE_HOLDER*)mpFileDesc;
	if (pFileHolder->pFileData)
		free(pFileHolder->pFileData);

	AAsset_seek(pFileHolder->pFile, 0, SEEK_SET);
	pFileHolder->pFileData = malloc(pFileHolder->size);
	AAsset_read(pFileHolder->pFile, pFileHolder->pFileData, pFileHolder->size);

	return pFileHolder->pFileData;
}
void KFileReader::ReleaseCopyInMemory()
{
	FILE_HOLDER* pFileHolder = (FILE_HOLDER*)mpFileDesc;
	if (pFileHolder->pFileData)
		free(pFileHolder->pFileData);
	pFileHolder->pFileData = NULL;
}